<template>
  <section
    class="OceVideo"
    @mousemove="mouse('enter')"
    @mouseleave="mouse('leave')"
    @dblclick="fullScreen"
    :class="{ 'full-screen': isFullScreen }"
  >
    <!-- <div
      v-if="!isLive"
      id="video"
      ref="video"
      class="video"
      :class="{ 'display-scale': displayScale !== 'speed' }"
      @contextmenu.prevent.capture.stop="onContextmenu"
    ></div> -->

    <!-- flvjs -->
    <div
      id="video"
      ref="video"
      class="video hideMenu"
      :class="{ 'display-scale': displayScale !== 'speed' , 'canplay': canplay}"
      @contextmenu.prevent.capture.stop="onContextmenu"
      @click.capture.stop="onClick"
      v-if="videoType == 'flvjs'"
    ></div>

    <!-- xgPlayer -->
    <div
      id="video"
      ref="video"
      class="video hideMenu"
      @contextmenu.prevent.capture.stop="onContextmenu"
      v-else
    ></div>

    <!-- 控制条 -->
    <div
      class="controlColumn"
      :style="{ bottom, opacity, height: isLive ? '40px' : '60px' }"
      @mouseenter="isMouseControl = true"
      @mouseleave="isMouseControl = false"
      @dblclick.stop
    >
      <div class="progress" v-if="!isLive">
        <oce-progress
          style="height: 20px; width: 100%"
          :formatter="formatter"
          :option="progOption"
          :assistantNum.sync="assistantNum"
          :axisNum.sync="axisNum"
          @intercept="intercept"
        ></oce-progress>
      </div>
      <div class="fun">
        <div class="left">
          <!-- <el-tooltip class="item" effect="dark" :content="isPlay ? '停止' : '播放'" placement="top"> -->
          <i
            :class="{
              iconfont: true,
              'icon-bofang': !isPlay,
              'icon-iconstop': isPlay,
            }"
            @click="playVideo(!isPlay)"
          />
          <!-- </el-tooltip> -->
          <div class="text" v-if="!isLive" style="width: 140px">
            {{ timeFormat(axisNum) + ' / ' + timeFormat(duration || 0) }}
          </div>
          <div
            class="text"
            v-if="!hasAudio"
            :style="{ width: !isLive ? '80px' : '' }"
          >
            {{ infoText + speed + 'KB/s' }}
          </div>
        </div>

        <div class="right">
          <div class="volume">
            <div class="slider">
              <el-slider
                :value="volume"
                :show-tooltip="false"
                @input="adjustVolume"
                vertical
                height="80px"
              ></el-slider>
            </div>

            <i
              class="cursor-pointer"
              :class="{
                iconfont: true,
                'icon-shengyinkai': volume,
                'icon-jingyin': !volume,
              }"
              @click="mute"
              slot="reference"
            />
          </div>
          <div class="times cursor-pointer" v-if="!isLive">
            <div class="select">
              <div
                v-for="(item, i) of timesList"
                :key="'times' + i"
                class="timesItem"
                :style="{ color: item.value == times.value ? '#1890FF' : '' }"
                @click="adjustTimes(item)"
              >
                {{ item.label }}
              </div>
            </div>

            <span>{{ times.value == 1 ? '倍速' : times.label }}</span>
          </div>
          <!-- <el-tooltip class="item" effect="dark" content="截图" placement="top"> -->
          <i class="iconfont icon-paizhao cursor-pointer" @click="screenshot" />
          <!-- </el-tooltip> -->

          <i class="el-icon-download cursor-pointer" v-if="!isLive" @click="downloadRecording" />

          <!-- <el-tooltip class="item" effect="dark" content="全屏" placement="top"> -->
          <i
            class="iconfont icon-quanping cursor-pointer"
            @click="fullScreen"
          />
          <!-- </el-tooltip> -->
        </div>
      </div>
    </div>
  </section>
</template>

<script>
// import flvjs from "flv.js";
// import { freeMediaUrl } from "@/utils/ts/mediaUrl";
import dayjs from 'dayjs'
import flvjsMixin from './flvjsMixin'
import xgPlayerMixin from './xgPlayerMixin'

export default {
  name: 'OceVideo',
  mixins: [flvjsMixin, xgPlayerMixin],
  data() {
    return {
      canplay: false,
      player: null,
      volume: 0, // 音量
      oldVolume: null,
      isPlay: true,
      realIsPlay: true, // 用户操作播放状态
      bottom: '-40px',
      opacity: 0,
      isFullScreen: false,
      isMouseControl: false,
      speed: 0,
      progOption: {
        max: 100,
        dataInterception: true,
      },
      axisNum: 0,
      assistantNum: 0,
      duration: 0,
      isDrag: false,
      timesList: [
        {
          label: '16.0x',
          value: 16,
        },
        {
          label: '8.0x',
          value: 8,
        },
        {
          label: '4.0x',
          value: 4,
        },
        {
          label: '2.0x',
          value: 2,
        },
        // {
        //   label: "1.75x",
        //   value: 1.75,
        // },
        {
          label: '1.5x',
          value: 1.5,
        },
        // {
        //   label: "1.25x",
        //   value: 1.25,
        // },
        {
          label: '1.0x',
          value: 1,
        },
        // {
        //   label: "0.75x",
        //   value: 0.75,
        // },
        {
          label: '0.5x',
          value: 0.5,
        },
        // {
        //   label: "0.25x",
        //   value: 0.25,
        // },
      ],
      times: {
        label: '1.0x',
        value: 1,
      },
      videoType: 'flvjs',
      connectTimeoutFlag: null, // 回连定时器标识
    }
  },
  props: {
    // ["url", "id", "displayScale", "realTime", "infoText", "hasAudio"]
    url: String,
    fileName: String,
    id: [String, Number],
    displayScale: {
      type: String,
      default: 'speed',
    },
    // 'flvjs' 'xgPlayer'
    playerType: {
      type: String,
      default: 'flvjs',
    },
    realTime: String,
    infoText: {
      type: String,
      default: () => {
        return ''
      },
    },
    hasAudio: {
      type: Boolean,
      default: false,
    },
    isLive: {
      type: Boolean,
      default: true,
    },
    basisUrl: String,
    freeMediaUrl: Function,
  },
  watch: {
    volume: {
      handler(val) {
        this.$emit('volumeChange', {
          id: this.id,
          volume: val,
        })
      },
    },
    url: {
      deep: true,
      handler(val) {
        if (!val) return
        this.destroy()
        this.$nextTick(() => {
          this.playVideo(true)
        })
      },
    },
  },
  created() {
    if (this.player) this.destroy()
    // console.log("created");
    this.$nextTick(() => {
      this.player = this.initDPlayer(this.$refs.video, this.url)
    })
    this.videoType = this.playerType.toString()
  },
  beforeDestroy() {
    this.destroy()
    this.freeMediaUrl && this.freeMediaUrl(this.basisUrl)
  },
  methods: {
    // 下载录像
    downloadRecording() {
      let bolbList = this.player.flvPlayer.getBolbList()
      // console.log('***********视频数据：',bolbList)
      let arr = []
      bolbList.forEach(item => {
        let temp = new Uint8Array(item)
        // arr = [...arr,...temp]
        arr.push(...temp)
      })
      // console.log('***********视频数据2：',arr)
      let uint8 = new Uint8Array(arr)
      // console.log(uint8);
      let arrayBuffer = uint8.buffer
      let blob = new Blob([arrayBuffer])
      // console.log(blob);
      let a = document.createElement('a')
      let data = new Date().getTime()
      // a.download = `导出视频${data}.mp4`
      a.download = `${this.fileName || data}.mp4`
      a.href = URL.createObjectURL(blob)
      a.click()
    },
    // 调整倍速
    adjustTimes(t) {
      this.times = t
      if (this.player?.video?.playbackRate)
        this.player.video.playbackRate = t.value
    },
    // 手动修改时间轴
    intercept(time) {
      // console.log(time)
      if (time < this.assistantNum) {
        let t = Math.floor(time)
        this.player.video.currentTime = t
        this.axisNum = t
      } else {
        this.player.video.currentTime = this.assistantNum
        this.axisNum = this.assistantNum
      }
    },
    // 秒数转换为时分秒格式
    timeFormat(time) {
      if (time == Infinity) time = 0
      let timeStr = ''
      let stringFormat = (i) => {
        i = Math.floor(i)
        return i < 10 ? `0${i}` : `${i}`
      }
      let minuteTime = 0
      let secondTime = 0
      let hourTime = 0
      if (time < 60) {
        timeStr = `00:${stringFormat(time)}`
      } else if (time >= 60 && time < 3600) {
        minuteTime = parseInt(time / 60)
        secondTime = parseInt(time % 60)
        timeStr = `${stringFormat(minuteTime)}:${stringFormat(secondTime)}`
      } else if (time >= 3600) {
        let _t = parseInt(time % 3600)
        hourTime = parseInt(time / 3600)
        minuteTime = parseInt(_t / 60)
        secondTime = parseInt(_t % 60)
        timeStr = `${stringFormat(hourTime)}:${stringFormat(
          minuteTime
        )}:${stringFormat(secondTime)}`
      }
      return timeStr || '00:00'
    },
    // 进度条气泡格式
    formatter(val) {
      return this.timeFormat(val)
    },
    // 切换显示比例 speed 4:3 16:9 filling
    updateDisplayScale() {
      this[this.videoType + 'UpdateDisplayScale']()
    },
    // 自定义单击事件
    onClick(e) {
      this.$el.click()
      this.$emit('click', e)
    },
    // 自定义右键事件
    onContextmenu(event) {
      this.$emit('contextmenu', {
        event,
        player: this.player,
        isPlay: this.isPlay,
        id: this.id,
      })
    },
    // 销毁
    destroy() {
      this[this.videoType + 'Destroy']()
    },
    // 截图
    screenshot() {
      const canvas = document.createElement('canvas')
      canvas.width = this.player.video.videoWidth
      canvas.height = this.player.video.videoHeight
      canvas
        .getContext('2d')
        .drawImage(this.player.video, 0, 0, canvas.width, canvas.height)

      let dataURL
      // let time = this.$ocean.moment().format('YYMMDDHHmm')
      let time = dayjs().format('YYMMDDHHmm')
      canvas.toBlob((blob) => {
        dataURL = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = dataURL
        link.download = this.infoText + '-' + time + '.png'
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(dataURL)
      })
    },
    // 调整音量
    adjustVolume(vol) {
      if (!this.player || this.volume === vol) return
      this.volume = vol
      this.player.volume(this.volume / 100, true, false)
    },
    // 静音
    mute() {
      if (this.volume) {
        this.oldVolume = this.volume
        this.volume = 0
      } else {
        this.volume = this.oldVolume || 50
        this.oldVolume = null
      }
      this.player.volume(this.volume / 100, true, false)
    },
    // 切换播放状态播放
    playVideo(isPlay) {
      this[this.videoType + 'PlayVideo'](isPlay)
    },
    // 全屏
    fullScreen() {
      if (this.isFullScreen) {
        if (document.exitFullscreen) {
          if (document.fullscreenElement) document.exitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
        if (typeof cfs != 'undefined' && cfs) {
          cfs.call(el)
        }
        this.isFullScreen = false
      } else {
        let el = document.documentElement
        let rfs =
          el.requestFullScreen ||
          el.webkitRequestFullScreen ||
          el.mozRequestFullScreen ||
          el.msRequestFullscreen
        if (typeof rfs != 'undefined' && rfs) {
          rfs.call(el)
        }
        // document.getElementsByClassName("app-main")[0].style.zIndex = "10";
        this.isFullScreen = true
        window.onresize = () => {
          if (!this.$ocean.checkFull()) {
            this.isFullScreen = false
            setTimeout(() => {
              this.updateDisplayScale()
            }, 50)
          }
        }
      }
      this.$nextTick(() => {
        this.updateDisplayScale()
      })
      // this.isFullScreen = !this.isFullScreen
    },
    // 监听鼠标
    mouse(state) {
      switch (state) {
        case 'enter':
          this.bottom = 0
          this.opacity = 1
          this.$ocean.debounce(
            () => {
              if (this.isMouseControl) {
                this.mouse('enter')
              } else {
                this.mouse('leave')
              }
            },
            3000,
            false
          )
          break
        case 'leave':
          this.bottom = '-40px'
          this.opacity = 0
          break
      }
    },
    // 初始化视频
    initDPlayer(container, url) {
      this.$nextTick(() => {
        this.updateDisplayScale()
      })
      return this[this.videoType + 'InitDPlayer'](container, url)
    },
  },
}
</script>

<style lang="scss" scoped>
.OceVideo {
  height: 100%;
  width: 100%;
  position: relative;
  overflow: hidden;
  background: black;

  .canplay{ 
    ::v-deep .diplayer-loading-icon{
      display: none  !important;
    }
  }

  & .focus {
    border: 2px green solid;
  }

  .video {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    ::v-deep .dplayer-menu {
      > :nth-last-child(-n + 3) {
        display: none;
      }
    }
  }
  .hideMenu {
    ::v-deep .dplayer-live-badge,
    ::v-deep .dplayer-controller-mask,
    ::v-deep .dplayer-controller {
      display: none;
    }
  }

  .display-scale {
    ::v-deep .dplayer-video-wrap {
      display: flex;
      justify-content: center;
      align-items: center;

      .dplayer-video {
        object-fit: fill;
      }
    }
  }

  .controlColumn {
    position: absolute;
    // height: 40px;
    width: 100%;
    color: #fff;
    // background: red;
    background-image: linear-gradient(
      rgba($color: #111, $alpha: 0.2),
      rgba($color: #000, $alpha: 0.7)
    );
    transition: bottom, opacity, 0.5s;
    .progress {
      padding: 0 10px;
    }
    .fun {
      display: flex;
      justify-content: space-between;
      width: 100%;
      position: absolute;
      i {
        width: 20px;
        height: 20px;
        margin: 10px;
        display: inline-block;
      }
      .left {
        display: flex;

        .text {
          height: 100%;
          line-height: 35px;
          padding-left: 8px;
        }
      }

      .right {
        display: flex;

        .volume {
          position: relative;

          .slider {
            width: 30px;
            height: 0;
            opacity: 0;
            overflow: hidden;
            position: absolute;
            top: 0;
            background: rgba($color: #444, $alpha: 0.5);
            transition: all 0.5s;
            padding-top: 10px;

            ::v-deep .el-slider__runway,
            ::v-deep .el-slider__runway,
            ::v-deep .el-slider__bar {
              height: 2px;
              width: 2px;
            }
            ::v-deep .el-slider__runway {
              margin: 0 14px;
            }
            ::v-deep .el-slider__button {
              width: 10px;
              height: 10px;
              background-color: #eee;
              border: 0px;
            }
            ::v-deep .el-slider__button-wrapper {
              // top: -16px
              left: -17px;
            }
          }

          &:hover {
            .slider {
              height: 100px;
              top: -100px;
              opacity: 1;
            }
          }
        }

        .times {
          height: 40px;
          line-height: 38px;
          padding: 0 5px 0 0;
          width: 45px;
          text-align: center;

          .select {
            width: 80px;
            height: 0;
            opacity: 0;
            overflow: hidden;
            position: absolute;
            transform: translateX(-25px);
            top: 0;
            background: rgba($color: #444, $alpha: 0.5);
            transition: all 0.5s;
            padding: 0px;
            text-align: center;
            line-height: 30px;

            .timesItem {
              padding: 0;
              margin: 0;
              &:hover {
                background-color: #414141;
              }
            }
          }

          &:hover {
            .select {
              height: 210px;
              top: -210px;
              opacity: 1;
            }
          }
        }
      }
    }
  }
}
.full-screen {
  height: 100vh;
  width: 100vw;
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
}
</style>
